package expression;

import vm.baseNativeUseFunction.NativeUseFunction;
import vm.runtime.NextVMRuntime;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BaseExpression {
    public static Object[] Deal(String[] Input, NextVMRuntime nextVMRuntime)
    throws Exception{
        Object[] objects = new Object[Input.length];
        int j = 0;
        for (String i : Input) {
            if (StringExpression.IsNumber(i)) {
                objects[j] = Integer.parseInt(i);
            }
            else if (StringExpression.getValueFromNextVM(i,nextVMRuntime) != null) {
                objects[j] = StringExpression.getValueFromNextVM(i,nextVMRuntime);
            }
            else if (NextVMRuntime.isRunFunction(i,nextVMRuntime) != null)
            {
                NextVMRuntime fn = NextVMRuntime.isRunFunction(i,nextVMRuntime);
                fn.run();
                objects[j] = fn.ReturnContent;
            }
            else if (NativeUseFunction.IsNativeUseFunction(i)) {
                String funcName = i.substring(0,i.indexOf("(")).trim();
                String Content = i.substring(i.indexOf("(")+1,i.lastIndexOf(")"));
                String regex = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)(?=([^\\(]*\\([^\\)]*\\))*[^\\)]*$)";
                String[] split = Content.split(regex);
                ArrayList<String> arrayList = new ArrayList<>();
                arrayList.add(funcName);
                arrayList.addAll(Arrays.asList(split));
                objects[j] = NativeUseFunction.run(arrayList.toArray(new String[0]), nextVMRuntime,i);
            }
            else {
                try {
                    objects[j] = StringExpression.getExpression(i,nextVMRuntime);
                }catch (Exception e) {
                    objects[j] = i;
                }
            }
            j++;
        }
        return objects;
    }
}
